from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import StructType, StringType, IntegerType

if __name__ == '__main__':
    # 构建SparkSession对象
    spark = SparkSession.builder. \
        appName("local[*]"). \
        config("spark.sql.shuffle.partitions", "4"). \
        getOrCreate()
    # appName 设置程序名称
    # config 设置常用属性。可以通过此来设置配置
    # 最后通过getOrCreate 创建 SparkSession对象

    # 从SparkSession中获取SparkContext
    sc = spark.sparkContext

    # TODO 1.加载数据
    df = spark.readStream \
        .format(source="kafka") \
        .option("kafka.bootstrap.servers", "node1:9092") \
        .option("subscribe", "testTopic") \
        .load()

    df.printSchema()

    # TODO 2.处理数据
    valueDS = df.selectExpr("CAST(value AS STRING)")
    # kafka传输的数据，固定值的名称为value，并且是二进制，需要转换成string

    # TODO 3.输出结果
    df.writeStream \
        .format(source="kafka") \
        .option("kafka.bootstrap.servers", "node1:9092") \
        .option("topic", "test2Topic") \
        .start() \
        .awaitTermination()  # TODO 4.启动并等待结束

    # TODO 5.关闭资源
    spark.stop()
